package com.woniuxy.bankb.datasource;

import java.io.IOException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.alibaba.druid.pool.DruidDataSource;

import io.seata.rm.datasource.DataSourceProxy;

@Configuration
public class DataSourceConfiguration {
	//@ConfigurationProperties该注解用于创建完对象之后，即将加入IOC容器时自动通过
	//prefix到application.yml文件中找到指定的配置信息，再将配置信息赋值给刚才创建的对象
	@Bean
	@ConfigurationProperties(prefix="spring.datasource")
	public DataSource druidDataSource() {
		DruidDataSource druidDataSource = new DruidDataSource();
		return druidDataSource;
	}
	
	//设置druid代理
	@Bean("dataSource")		//指定名字为dataSource
	@Primary				//优先使用，bean名字、类型相同时
	public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
		return new DataSourceProxy(druidDataSource);
	}
	
	//设置SQLsessionfactory
	@Bean
	public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		//设置数据源
		sqlSessionFactoryBean.setDataSource(dataSourceProxy);
		//加载mapper.xml
//		sqlSessionFactoryBean.setMapperLocations(
//				new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml"));
		//设置事务工厂，用于创建事务
		sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
		//
		return sqlSessionFactoryBean.getObject();
	}
	
}
